package com.xxx.lib.net.helper

import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.xxx.lib.SPConfig
import com.xxx.lib.constant.KeyAccount
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

/**
 * cookie协助类
 */
internal class CookieHelper : CookieJar {

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        val cookie = SPConfig.spUtilsAccount.getString(KeyAccount.KEY_COOKIE)
        return if (cookie.isNotBlank()) {
            GsonUtils.fromJson(cookie, object : TypeToken<List<Cookie>>() {}.type)
        } else {
            emptyList()
        }
    }

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        val cookie = GsonUtils.toJson(cookies)
        if (cookie.contains("ci_session_new")) {
            SPConfig.spUtilsAccount.put(KeyAccount.KEY_COOKIE, cookie)
        }
    }
}